package web;

import service.LoginService;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author fire'ge
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到用户输入的信息，并且进行分割
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获得连接（JDBC_utils类是自己编写封装的一个获取连接工具类）
        User user = null;
        try {
            user=LoginService.checkLogin(username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=utf-8");

            //这里是对用户提交登录表格信息之后去进行数据库查询，查询得到的user对象放入到session中再进行转发
            if (user != null ){
                HttpSession session = request.getSession();
                session.setAttribute("username","123123123");
                session.setAttribute("user",user);
                request.getRequestDispatcher("/jsp/MainMenu.jsp").forward(request,response);
                       }
            else {
                request.setAttribute("login_msg","登录失败，请检查密码是否正确");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
            }

    }

        @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
